import type { Router } from 'vue-router';
import { to as tos } from 'await-to-js';

import { isHttp } from '@/utils/validate';
import { getToken } from '@/utils/auth';
import { useUserStore } from '@/store/modules/user';
import { isReLogin } from '@/utils/request';
import usePermissionStore from '@/store/modules/permission';

const whiteList = ['/login', '/register', '/social-callback'];

export default (router: Router) => {
  router.beforeEach(async (to, _, next) => {
    if (getToken()) {
      if (to.path === '/login') {
        next({ path: '/' });
      } else if (whiteList.includes(to.path as string)) {
        next();
      } else {
        if (useUserStore().roles.length === 0) {
          isReLogin.show = true;
          // 判断当前用户是否已拉取完user_info信息
          const [err] = await tos(useUserStore().getInfo());
          if (err) {
            await useUserStore().logout();
            next({ path: '/' });
          } else {
            isReLogin.show = false;
            const accessRoutes = await usePermissionStore().generateRoutes();
            // 根据roles权限生成可访问的路由表
            accessRoutes.forEach((route: any) => {
              if (!isHttp(route.path)) {
                // 动态添加可访问路由表
                router.addRoute(route);
              }
            });
            // hack方法 确保addRoutes已完成
            next({
              path: to.path as any,
              replace: true,
              params: to.params,
              query: to.query,
              hash: to.hash,
              name: to.name as string,
            });
          }
        } else {
          next();
        }
      }
    } else {
      // 没有token
      if (whiteList.includes(to.path as string)) {
        // 在免登录白名单，直接进入
        next();
      } else {
        const redirect = encodeURIComponent(to.fullPath || '/');
        // 否则全部重定向到登录页
        next(`/login?redirect=${redirect}`);
      }
    }
  });
};
